package com.lumlord.common.shiro.config;

import com.lumlord.common.annotation.Api;
import com.lumlord.common.domain.LumlordApi;
import com.lumlord.common.exception.BusinessException;
import com.lumlord.common.spring.RequestJsonBody;
import com.lumlord.util.MD5Util;
import com.lumlord.util.SignTool;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import com.lumlord.common.domain.Result;
import com.lumlord.common.domain.User;
import com.lumlord.common.shiro.util.JWTToken;
import com.lumlord.common.shiro.util.JwtUtils;
import com.lumlord.common.shiro.util.ShiroUtils;
import com.lumlord.service.SystemUserService;
import com.lumlord.util.RedisUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Component
public class JwtAuthFilter extends AuthenticatingFilter {
    private final Logger log = LoggerFactory.getLogger(JwtAuthFilter.class);

    public static final String TOOKEN_NAME = "lumlord_token";
    public static final String LUMLORD_REQUEST_JSON = "LUMLORD_REQUEST_JSON";
    private static final int tokenRefreshInterval = 300;

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        // if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) //
        // 对于OPTION请求做拦截，不做token校验
        fillCorsHeader(httpServletRequest, httpServletResponse);
        // return false;
        return super.preHandle(request, response);
    }

    @Override
    protected void postHandle(ServletRequest request, ServletResponse response) {
        this.fillCorsHeader(WebUtils.toHttp(request), WebUtils.toHttp(response));
        request.setAttribute("jwtShiroFilter.FILTERED", true);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        shiroSupportSession(httpServletRequest); //支持shiro 新建session
        //

        if (httpServletRequest.getRequestURL().indexOf("webSocket") != -1||httpServletRequest.getRequestURL().indexOf("api-docs") != -1|| httpServletRequest.getRequestURL().indexOf("druid") != -1|| httpServletRequest.getRequestURL().indexOf("swagger") != -1) {
            return true;
        }

        if (isAllowed(httpServletRequest, httpServletResponse)) { //api 设置权限过滤页面  免sign
            return true;
        }

        if (this.isLoginRequest(request, response)){
            return true;
        }


      /*  try {
            if (!isAllowedSign(httpServletRequest)) {
                Result.writeJson(response, Result.error("sign 认证失败。"));
                return false;
            }
        } catch (BusinessException e) {
            Result.writeJson(response, Result.error(e.getMessage()));
            return false;
        }*/

        String jwtToken = getAuthzHeader(request);
        if (jwtToken == null) {
            Result.writeJson(response, Result.errorLogin("Not found any token !"));
            return false;
        } else { // redis 中不存在
            User user = ShiroUtils.getUserByToken(jwtToken);
             if (null == user) { // reSet user !
                Result.writeJson(response, Result.errorLogin("please login again! your token is invalid ! "));
                return false;
            } else {
                if(!jwtToken.equals(user.getTooken())){ //强制 修改成  tooken 用户
                    Result.writeJson(response, Result.errorLogin("please login again! your token is timeOut ! "));
                    return false;
                }

                 if(request.getParameter("parentUrl")!=null){ //注入action 不走权限判断
                    return true;
                 }

               // if(!roleFilter(user,httpServletRequest,httpServletResponse,response)){
                 //    return  false;
                 // }
                   return true;
            }
        }
    }



    private boolean roleFilter(User user,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,ServletResponse response) {
       /* if (!getUserRoles(user.getRoleId(), httpServletRequest, httpServletResponse)) {
                Result.writeJson(response, Result.error("没有权限，请进行授权!"));
                return false;
        }*/
       return true;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        return super.executeLogin(request, response);
    }



    /**
     * 这里重写了父类的方法，使用自己定义的Token类，提交给shiro。
     * 这个方法返回null的话会直接抛出异常，进入isAccessAllowed（）的异常处理逻辑。 ### gpf bug
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) {
        String jwtToken = getAuthzHeader(servletRequest);
        if (StringUtils.isNotBlank(jwtToken) && !jwtUtils.isTokenExpired(jwtToken)) {
            return new JWTToken(jwtToken);
        } else if (jwtUtils.isTokenExpired(jwtToken)) {
            return new JWTToken(jwtToken); // ShiroUtils.getSubjct();
        }
        return null;
    }

    /**
     * 如果这个Filter在之前isAccessAllowed（）方法中返回false,则会进入这个方法。我们这里直接返回错误的response
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletResponse httpResponse = WebUtils.toHttp(servletResponse);
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json;charset=UTF-8");
        httpResponse.setStatus(200);
        fillCorsHeader(WebUtils.toHttp(servletRequest), httpResponse);
        return false;
    }

    /**
     * 如果Shiro Login认证成功，会进入该方法，等同于用户名密码登录成功，我们这里还判断了是否要刷新Token
     */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
                                     ServletResponse response) throws Exception {
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        /*
         * if (token instanceof JWTToken) { JWTToken jwtToken = (JWTToken) token;
         * boolean shouldRefresh =
         * shouldTokenRefresh(jwtUtils.getIssuedAt(jwtToken.getToken())); if
         * (shouldRefresh) {
         * createAndWriteTooken(jwtUtils.getUsername(jwtToken.getToken()),
         * 1,httpResponse); } }
         */
        return true;
    }

    /**
     * 如果调用shiro的login认证失败，会回调这个方法，这里我们什么都不做，因为逻辑放到了onAccessDenied（）中。
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
                                     ServletResponse response) {
        log.error("Validate token fail, token:{}, error:{}", token.toString(), e.getMessage());
        Result.writeJson(response, Result.error("Validate token fail !"));
        return false;
    }

    public String getAuthzHeader(ServletRequest request) {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        String header = httpRequest.getHeader(TOOKEN_NAME);
        String tooken = StringUtils.removeStart(header, "Bearer ");
        if (request.getParameter(TOOKEN_NAME) != null) {
            return request.getParameter(TOOKEN_NAME);
        } else
            return tooken;
    }

    protected boolean shouldTokenRefresh(Date issueAt) {
        LocalDateTime issueTime = LocalDateTime.ofInstant(issueAt.toInstant(), ZoneId.systemDefault());
        return LocalDateTime.now().minusSeconds(tokenRefreshInterval).isAfter(issueTime);
    }

    public void fillCorsHeader(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers",
                httpServletRequest.getHeader("Access-Control-Request-Headers"));
    }


    @Nullable
    private HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
        if (dispatcherServlet.getHandlerMappings() != null) {
            Iterator var2 = dispatcherServlet.getHandlerMappings().iterator();
            while (var2.hasNext()) {
                HandlerMapping mapping = (HandlerMapping) var2.next();
                HandlerExecutionChain handler = mapping.getHandler(request);
                if (handler != null) {
                    return handler;
                }
            }
        }

        return null;
    }

    private void shiroSupportSession(HttpServletRequest request) {
        request.setAttribute(DefaultSubjectContext.SESSION_CREATION_ENABLED, true);
    }

    /**
     * 判断签名是否，通过
     *
     * @return true 通过
     */
    private boolean isAllowedSign(HttpServletRequest request) throws BusinessException {
        String json = requestJsonBody.getRequestBody(request);
        SignTool signTool = new SignTool();
        String source = signTool.buildSign(request.getRequestURI(), json);
        if (MD5Util.isEqualsToMd5UpperCase(source, signTool.getClientSign())||signTool.getClientSign().equals("true")) {
            return true;
        } else {

            throw new BusinessException("MD5 串 = " + signTool.getSignMd5());
        }

    }

    public HandlerMethod getMethod(HttpServletRequest request, HttpServletResponse httpServletResponse) {
        HandlerExecutionChain handlerExecutionChain = null;
        try {
            handlerExecutionChain = getHandler(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null == handlerExecutionChain) {
            return null;
        } else {
            Object obj = handlerExecutionChain.getHandler();

            if (obj instanceof HandlerMethod) {
                HandlerMethod bf = (HandlerMethod) obj;
                return bf;
            }
            return null;
        }

    }

    /**
     * 根据配置判断是否，通过
     *
     * @return true通过
     */
    private boolean isAllowed(HttpServletRequest request, HttpServletResponse httpServletResponse) {
        HandlerMethod handlerMethod = getMethod(request, httpServletResponse);
        if (null != handlerMethod) {
            Api api = handlerMethod.getMethod().getAnnotation(Api.class);
            if (null!=api&&api.isAllow()) {
                if (!api.isJsonRequest()) { //不是json请求
                    request.setAttribute(LUMLORD_REQUEST_JSON, true);
                }
                return true;
            }
            ;
            return false;
        } else {
            return false;
        }

    }

    /**
     * 签名信息校验
     **/
    private boolean signValidate() {
        return true;
    }

    @Autowired
    private SystemUserService systemUserService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private DispatcherServlet dispatcherServlet;
    @Autowired
    private RequestJsonBody requestJsonBody;
}
